#pragma once

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>

typedef Bintree Datatype;

typedef struct Stack
{
	Datatype* head;
	int top;
	int capacity;
}ST;

void StackInit(ST* ps);
void StackDestroy(ST* ps);
void StackPush(ST* ps, Datatype x);
void StackPop(ST* ps);
Datatype StackRead(ST* ps);
bool Stackempty(ST* ps);
bool isValid(char* s);

void StackInit(ST* ps)
{
    assert(ps);
    ps->head = NULL;
    ps->top = 0;
    ps->capacity = 0;
}

void StackDestroy(ST* ps)
{
    assert(ps);
    free(ps->head);
    ps->head = NULL;
    ps->capacity = ps->top = 0;
}

void StackPush(ST* ps, Datatype x)
{
    assert(ps);
    if (ps->top == ps->capacity)
    {
        int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
        Datatype* new1 = (Datatype*)realloc(ps->head, sizeof(Datatype) * newcapacity);
        if (new1 == NULL)
        {
            perror("malloc error");
            exit(-1);
        }
        ps->capacity = newcapacity;
        ps->head = new1;
    }
    ps->head[ps->top] = x;
    ps->top++;
}

void StackPop(ST* ps)
{
    assert(ps);
    assert(!Stackempty(ps));

    ps->top--;
}

Datatype StackRead(ST* ps)
{
    assert(ps);
    assert(!Stackempty(ps));

    return ps->head[ps->top - 1];
}

bool Stackempty(ST* ps)
{
    assert(ps);
    return ps->top == 0;
}


bool isValid(char* s)
{
    ST ps;
    StackInit(&ps);
    char* cur = s;
    while (*cur)
    {
        if (*cur == '('
            || *cur == '['
            || *cur == '{')
        {
            StackPush(&ps, *cur);
        }
        else
        {
            if ((StackRead(&ps) == '(' && *cur == ')')
                || (StackRead(&ps) == '[' && *cur == ']')
                || (StackRead(&ps) == '{' && *cur == '}'))
            {
                StackPop(&ps);
            }
            else
            {
                StackDestroy(&ps);
                return false;
            }
        }
        cur++;
    }
    if (Stackempty(&ps))
    {
        StackDestroy(&ps);
        return true;
    }
    else
    {
        StackDestroy(&ps);
        return false;
    }

}